/* eslint-disable eqeqeq */
import { message } from 'antd';
import { routerRedux } from 'dva';
import api from '../api';
import { clearStorage, clearCookie, getCookie, setCookie } from '../utils/commonFunc';
import { environmentPath } from '../utils/environmentPath';

export default {
  namespace: 'login',

  state: {
    status: undefined,
    token: undefined,
    tokenTime: undefined,
    cdxUrl: '/',
    // 1，登出跳转到maat登陆界面（互联网侧跳转到互联网登陆界面，堡垒机侧跳转到堡垒机登陆界面)
    //  2，登出跳转到incos登录页==》这里退出到https://pb.htsc.com.cn/
    systemCode: undefined,
  },

  effects: {
    // maat登录
    *urlLogin({ payload, callback }, { call, put, select }) {
      const response = yield call(api.user.urlLogin, payload);
      let msg = 'success';
      if (response) {
        // console.log(response.code);
        switch (response.code) {
          case '0':
            msg = 'success';
            break;
          case '-1':
            msg = '系统异常，登录失败';
            break;
          case '-2':
            msg = '用户名/密码为空';
            break;
          case '-3':
            msg = '用户名/密码错误';
            break;
          case '-4':
            msg = '账号被锁定';
            break;
          case '-5':
            msg = '账号无效';
            break;
          default:
            msg = '登录失败';
            break;
        }
        if (msg == 'success') {
          console.log('1-login.js--', response.data.userId);
          localStorage.setItem('antd-pro-userId', response.data.userId); // 将userId存入localStorage中
          localStorage.setItem('antd-pro-token', response.data.hToken); // 将token存入localStorage中
          callback(true);
        } else {
          message.error(msg);
        }
      }
    },
    // heimdall 获取短信验证码
    *getVerificationCode({ payload, callback }, { call, put, select }) {
      const response = yield call(api.user.getVerificationCode, payload);
      if (response?.code == '0') {
        console.log(response.msg);
        message.success('验证码发送成功!');
      } else if (response) {
        let msg = '';
        console.log(response.code);
        switch (Number(response.code)) {
          case 11017:
            msg = '该号码未注册，请检查号码的正确性!';
            break;
          case 14024:
            msg = '请勿频繁发送验证码!';
            break;
          default:
            msg = '获取验证码失败，请联系管理员!';
        }
        callback();
        message.error(msg);
      } else {
        callback();
        message.error('获取验证码失败，请联系管理员!');
      }
    },
    // heimdall 登录
    *heimdallLogin({ payload, callback }, { call, put, select }) {
      const response = yield call(api.user.heimdallLogin, payload);
      if (response?.status == 0) {
        callback(true);
        localStorage.setItem('antd-pro-token', getCookie('HeimadllToken'));
      } else if (response) {
        if (response.status == 11005) {
          // 首次登录用户 需要重置密码
          sessionStorage.setItem('resetUser', payload.username);
          message.warning('您的密码安全性较低，请重置密码！');
          yield put(routerRedux.push('/resetPassword'));
          return;
        }
        console.log('heimdall登录报错');
        let msg = '';
        switch (response.status) {
          case 10009:
            msg = '用户名密码错误!';
            break;
          case 10032:
            msg = '您的账户已锁定，请1分钟之后重试！';
            break;
          case 11004:
            msg = '账户已冻结，请联系管理员!';
            break;
          case 14028:
            msg = '验证码错误!';
            break;
          case 14027:
            msg = '验证码失效!';
            break;
          case -1:
            msg = '系统繁忙，请稍后再试!';
            break;
          default:
            msg = '登录失败，请联系管理员!';
        }
        message.error(msg);
      } else {
        message.error('登录失败，请联系管理员!');
      }
    },
    // 获取登出code 用于判断退出之后跳转的登录地址
    *getSystemCode({ payload }, { call, put, select }) {
      const response = yield call(api.user.getSystemCode, payload);
      if (!response || response?.code != 0) console.log('获取所在系统code失败：', response?.msg); // 这里报错并不影响用户使用，所以没有弹窗报错
      yield put({
        type: 'setState',
        payload: {
          systemCode: response?.data?.systemCode,
        },
      });
    },
    // 单纯的退出到登录页 或者在系统无权限的时候调用 不做额外操作 单纯确定退出的login页面地址
    *logout(_, { put, select }) {
      try {
      } finally {
        const systemCode = yield select((state) => state.login.systemCode);
        console.log('当前系统code:', systemCode);
        if (systemCode == '1') {
          // 按当前根地址跳转到登录页
          yield put(routerRedux.push('/login'));
        } else if (systemCode == '2') {
          // 登出跳转到incos登录页
          window.location.href = 'https://pb.htsc.com.cn/';
        } else {
          // 默认按当前根地址跳转到登录页
          yield put(routerRedux.push('/login'));
        }
        yield put({
          type: 'setState',
          payload: {
            systemCode: undefined,
          },
        });
      }
    },
    // 点击 退出按钮时 进入
    *logout2(_, { call, put, select }) {
      // 退出之后 统一删除storage数据
      // 研究管理-城投债信用利差需要记住查询条件，推出后重新设置
      const creditSpreadAnalysisSearchKey = `creditSpreadAnalysisSearch${localStorage.getItem('antd-pro-userId')}`;
      const creditSpreadAnalysisSearch = localStorage.getItem(`creditSpreadAnalysisSearch${localStorage.getItem('antd-pro-userId')}`); // 城投债信用利差需要保留查询条件
      clearStorage();
      localStorage.setItem(creditSpreadAnalysisSearchKey, creditSpreadAnalysisSearch);
      const isInner = environmentPath();
      console.log('*******', isInner);
      if (isInner) {
        // 内网 保持原有登出操作
        yield put({ type: 'logout' });
      } else {
        const response = yield call(api.user.heimdallLogout);
        clearCookie(); // 退出删除cookies
        if (response?.status == 0) {
          // 跳转到对应得登录地址
          yield put({ type: 'logout' });
        } else if (response) {
          let msg = '';
          switch (response.status) {
            case 10001:
              msg = '缺少登录身份，系统未登录!';
              break;
            case 10007:
              msg = '令牌已过期，系统未登录!';
              break;
            case -1:
              msg = '系统繁忙，请稍后再试!';
              break;
            default:
              msg = '退出失败，请联系管理员!';
          }
          message.error(msg);
          // 跳转到对应得登录地址
          yield put({ type: 'logout' });
        } else {
          // 跳转到对应得登录地址
          yield put({ type: 'logout' });
          message.error('退出失败，请联系管理员!');
        }
      }
    },
    // 注册极验接口
    *registerGeetest({ payload, callback }, { call, put, select }) {
      const response = yield call(api.user.registerGeetest, payload);
      //   let response={
      //     "code": 0,
      //     "success": true,
      //     "message": "register success",
      //     "class": "com.htsc.heimdall.entity.geetest.GeeTestResult",
      //     "value": {
      //         "static_servers": [
      //             "221.6.6.236:8888"
      //         ],
      //         "slide": "www/js/slide.1.0.6.js",
      //         "challenge": "cc632cf83fe85224793dc5a303dbfcb8",
      //         "api_server": "221.6.6.236:8888",
      //         "fullpage": "www/js/fullpage.1.0.8.js",
      //         "type": "fullpage",
      //         "click": "www/js/click.1.0.4.js",
      //         "cid": "16e82c8fef5afbc8f50ae2332c1bc376",
      //         offline:true,
      //     }
      // }
      if (response?.code == 0) {
        callback(response.value);
      } else {
        callback();
        message.error('验证码注册失败!');
      }
    },
    // 极验接口 二次校验
    *validateGeetest({ payload, callback }, { call, put, select }) {
      const response = yield call(api.user.validateGeetest, payload);
      callback(response);
    },
    // 极验接口 二次校验 备用接口 离线可用
    *failbackValidate({ payload, callback }, { call, put, select }) {
      const response = yield call(api.user.failbackValidate, payload);
      callback(response);
    },
  },

  reducers: {
    setState(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};
